import loginBg from "@/assets/image/login_bg.png";
import logoImg from "@/assets/image/logo_img.png";
import { getCode, getConfigByCode, getDingTalkUrlByCode } from "@/api/ssoMFauth";
import { mapMutations } from "vuex";
import { setEncryptData, getDecryptData } from "@/utils/jsencrypt"
export default {
  components: {},
  data() {
    return {
      loading: false,
      loginBg,    // 背景
      logoImg,   // 莫凡logo
      username: "",     //  账号
      password: "",     //  密码
      canClick: false,
      redirectObj: null,
    };
  },
  watch: {},
  mounted() {
    //code是登录所需最终参数
    const { code } = this.$route.query;
    if (code) {
      //登录接口
      this.handleGetDataByCode(code);
    }else{
      this.$message({
        message: "缺少授权码",
        type: "error",
      });
    }
  },
  methods: {
    /**
     * 查询配置的授权回调地址
     * @param {*} code 
     */
    async handleGetDataByCode(code) {
      const res = await getConfigByCode({code});
      if(res && res.success && res.data && res.data.callback_url){
        this.redirectObj = res.data;
        this.canClick = true;
      }else{
        this.$message({
          message: "授权回调地址获取失败",
          type: "error",
        });
      }
    },
    /**
     * 账号登录
     */
    async handleLoginAccount(){
      if(!this.canClick) return this.$message({ message: "缺少授权码", type: "error" });
      if(!this.username || !this.password) return this.$message({ message: "请填写用户名和密码", type: "info" });
      const _loginEncrypt = await setEncryptData({username: this.username, password: this.password});
      const loginRes = await getCode({
        loginEncrypt: _loginEncrypt
      });
      if(loginRes && loginRes.success && loginRes.data){
        window.location.href = this.redirectObj.callback_url+"?code="+loginRes.data+"&app_code="+ this.redirectObj.app_code;
      }else{
        this.$message({
          message: "账号或密码错误",
          type: "error",
        });
      }
    },
    /**
     * 钉钉登录
     */
    async handleLoginDingTalk(){
      if(!this.canClick) return this.$message({ message: "缺少授权码", type: "error" });
      const dingTalkRes = await getDingTalkUrlByCode({code: this.redirectObj.app_code});
      if(dingTalkRes && dingTalkRes.success && dingTalkRes.data){
        window.location.href = dingTalkRes.data;
      }else{
        this.$message({
          message: "账号或密码错误",
          type: "error",
        });
      }
    },
    /**
     * 微信登录
     */
    handleLoginWechat(){
      if(!this.canClick) return this.$message({ message: "缺少授权码", type: "error" });
      this.$message({
        message: "功能开发中...",
      });
    },
    /**
     * 跳转莫凡官网
     */
    toMourefun(){
      window.open("https://www.morefun.me/", "_blank");
    },
    // 授权地址
    async getAccredit() {
      await getAddress({state: "morefunoa"}).then((res) => {
        window.location.replace(res.data);
      });
    }
  },
};